import axios from 'axios';
import { ElMessage } from 'element-plus';
import { LEANCLOUD } from './config';

// 创建axios实例
const service = axios.create({
  baseURL: LEANCLOUD.API_BASE_URL, // 设置API基础URL
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
    'X-LC-Id': LEANCLOUD.APP_ID, // LeanCloud的AppID
    'X-LC-Key': LEANCLOUD.APP_KEY, // LeanCloud的AppKey
  },
});

// 添加Master Key支持的请求实例
export const serviceMaster = axios.create({
  baseURL: LEANCLOUD.API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'X-LC-Id': LEANCLOUD.APP_ID,
    'X-LC-Key': `${LEANCLOUD.MASTER_KEY},master`, // 使用Master Key
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在请求发送前，可以在这里添加一些逻辑，例如添加token
    const token = localStorage.getItem('sessionToken');
    if (token) {
      config.headers['X-LC-Session'] = token;
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// Master Key请求拦截器
serviceMaster.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('sessionToken');
    if (token) {
      config.headers['X-LC-Session'] = token;
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 直接返回响应数据，不包含AxiosResponse的其他信息
    console.log('API响应数据:', response.data);
    return response.data;
  },
  (error) => {
    console.error('响应错误:', error);
    let message = '请求失败';
    if (error.response) {
      const { status, data } = error.response;
      message = data.error || `请求错误: ${status}`;
    } else if (error.message) {
      message = error.message;
    }
    
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

// Master Key响应拦截器
serviceMaster.interceptors.response.use(
  (response) => {
    console.log('Master API响应数据:', response.data);
    return response.data;
  },
  (error) => {
    console.error('响应错误:', error);
    let message = '请求失败';
    if (error.response) {
      const { status, data } = error.response;
      message = data.error || `请求错误: ${status}`;
    } else if (error.message) {
      message = error.message;
    }
    
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service; 